//
//  ConcurrentProcessor.m
//  精通Objective-C
//
//  Created by 花强 on 2018/1/2.
//  Copyright © 2018年 花强. All rights reserved.
//

#import "ConcurrentProcessor.h"

@interface ConcurrentProcessor()//类扩展 为computeResult属性重启写入操作

@property (readwrite) NSInteger computeResult;

@end

@implementation ConcurrentProcessor{
    //线程管理和同步的私有实例变量
    NSString * computeID;   //@synchronize指令锁定的唯一对象
    NSUInteger computeTasks;//并行计算任务的计数
    NSLock * computeLock;   //锁对象
}

-(instancetype)init{
    if (self = [super init]) {
        _isFinished = NO;
        _computeResult = 0;
        computeLock = [NSLock new];
        computeID = @"1";
        computeTasks = 0;
    }
    return self;
}

-(void)computeTask:(id)data{
    NSAssert([data isKindOfClass:[NSNumber class]], @"Not an NSNumber instance");
    NSUInteger computations = [data unsignedIntegerValue];
    
    @autoreleasepool{
        @try{
            //获取锁并增加活动任务的计数
            if ([[NSThread currentThread] isCancelled]) {
                return;
            }
            @synchronized(computeID){
                computeTasks++;
            }
            
            //获取锁并执行关键代码部分中的计算操作
            [computeLock lock];
            if ([[NSThread currentThread] isCancelled]) {
                [computeLock unlock];
                return;
            }
            
            NSLog(@"Performing computations %ld",computations);
            for (int ii = 0; ii < computations; ii++) {
                self.computeResult = self.computeResult + 1;
            }
            [computeLock unlock];
            
            //模拟额外的处理时间（在关键部分之外的其他操作）
            [NSThread sleepForTimeInterval:1.0];
            
            //减少活动任务数，如果数量为0，则更新标志位
            @synchronized(computeID){
                computeTasks--;
                if (!computeTasks) {
                    self.isFinished = YES;
                }
            }
        }
        @catch(NSException * ex){
            
        }
    }
}

@end
